
# ==============================================================================
# DESCRIPTION ----
# ==============================================================================

# This code provides financial descriptive statistics from Nikkei NEEDS, 
# including financials by amakudari and government loan status. 

# ==============================================================================
# LIBRARIES AND IMPORT ----
# ==============================================================================

# Disable scientific notation
options(scipen=999)

# Libraries
library(tidyverse)
library(modelsummary)
library(ggridges)
library(viridis)
library(naniar)
library(visdat)
library(hablar)
library(kableExtra)
library(scales)
library(gridExtra)

# Data import
load("data/loans_amakudari.Rdata")
load("data/nikkei_financials_loans.Rdata")
load("data/nikkei_financials.Rdata")

# ==============================================================================
# FINANCIALS BY AMAKUDARI STATUS ----
# ==============================================================================

# Summarize data
financials_amakudari <- nikkei_time %>% 
  group_by(nikkei_code) %>%
  summarize(
    amakudari_n = sum(amakudari_n),
    employees = mean(employees, na.rm = TRUE),
    amakudari_employee = mean(employees, na.rm = TRUE)/sum(amakudari_n),
    total_assets = mean(total_assets, na.rm = TRUE), 
    total_liabilities = mean(total_liabilities, na.rm = TRUE), 
    operating_revenue = mean(operating_revenue, na.rm = TRUE),
    gross_profit = mean(gross_profit, na.rm = TRUE), 
    roi = mean(roi, na.rm = TRUE), 
    ebitda = mean(ebitda, na.rm = TRUE), 
    reserve_ratio = mean(reserve_ratio, na.rm = TRUE),
    roe = mean(roe)
  ) %>%
  rationalize() %>%
  mutate(amakudari = if_else(amakudari_n == 1, "Amakudari", "No amakudari"))

# Set ggplot styling
gglayers = list(
  theme_classic() +
    theme(
      legend.position="none",
      panel.grid.major.y = element_line(colour = "grey95"),
      panel.spacing = unit(0.1, "lines"),
      axis.text.x = element_text(size = 10),
      axis.text.y = element_text(size = 10),
      plot.title = element_text(size=10)
    ),
  xlab(""), 
  ylab("")
)

#### Plot financials ####
employ_0 <- with(financials_amakudari, mean(employees[amakudari_n == 0], na.rm = TRUE))
employ_1 <- with(financials_amakudari, mean(employees[amakudari_n > 0], na.rm = TRUE))

# Employees
employees <- financials_amakudari %>%
  ggplot(aes(x = employees, y = amakudari, fill = ..x..)) +
  geom_density_ridges_gradient(scale = 2, rel_min_height = 0.005,
                               gradient_lwd = 2, color = "white", size = 0.05) +
  scale_fill_viridis(alpha = 0.8) +
  scale_x_continuous(limits = c(0, 60000), breaks=seq(0, 60000, 10000)) +
  ggtitle("Total employees") +
  gglayers +
  theme(plot.margin=unit(c(0.25,0.25,-0.25,0.25), "cm"))

# Assets
assets <- financials_amakudari %>%
  ggplot(aes(x = log(total_assets), y = amakudari, fill = ..x..)) +
  geom_density_ridges_gradient(scale = 2, rel_min_height = 0.005,
                               gradient_lwd = 2, color = "white", size = 0.05) +
  scale_fill_viridis(alpha = 0.8) +
  ggtitle("Log total assets") +
  gglayers +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank()) +
  theme(plot.margin=unit(c(0.25,0.25,-0.25, 1.5), "cm"))

# Liabilities
liabilities <- financials_amakudari %>%
  ggplot(aes(x = log(total_liabilities), y = amakudari, fill = ..x..)) +
  geom_density_ridges_gradient(scale = 2, rel_min_height = 0.005,
                               gradient_lwd = 2, color = "white", size = 0.05) +
  scale_fill_viridis(alpha = 0.8) +
  ggtitle("Log total liabilities") +
  gglayers +
  theme(plot.margin=unit(c(0.25,0.25,-0.25,0.25), "cm"))

# Revenue
revenue <- financials_amakudari %>%
  ggplot(aes(x = log(operating_revenue), y = amakudari, fill = ..x..)) +
  geom_density_ridges_gradient(scale = 2, rel_min_height = 0.005,
                               gradient_lwd = 2, color = "white", size = 0.05) +
  scale_fill_viridis(alpha = 0.8) +
  ggtitle("Log net revenue") +
  gglayers +
  theme(plot.margin=unit(c(0.25,0.25,-0.25,0.25), "cm"))

# Profit
profit <- financials_amakudari %>%
  ggplot(aes(x = log(gross_profit), y = amakudari, fill = ..x..)) +
  geom_density_ridges_gradient(scale = 2, rel_min_height = 0.005,
                               gradient_lwd = 2, color = "white", size = 0.05) +
  scale_fill_viridis(alpha = 0.8) +
  ggtitle("Log gross profit") +
  gglayers +
  theme(plot.margin=unit(c(0.25,0.25,-0.25,0.25), "cm"))

# EBITDA
ebitda <- financials_amakudari %>%
  ggplot(aes(x = log(ebitda), y = amakudari, fill = ..x..)) +
  geom_density_ridges_gradient(scale = 2, rel_min_height = 0.005,
                               gradient_lwd = 2, color = "white", size = 0.05) +
  scale_fill_viridis(alpha = 0.8) +
  ggtitle("Log EBITDA") +
  gglayers +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank()) +
  theme(plot.margin=unit(c(0.25,0.25,-0.25, 1.5), "cm"))

# Return on investment
roi <- financials_amakudari %>%
  ggplot(aes(x = roi, y = amakudari, fill = ..x..)) +
  geom_density_ridges_gradient(scale = 2, rel_min_height = 0.005,
                               gradient_lwd = 2, color = "white", size = 0.05) +
  scale_fill_viridis(alpha = 0.8) +
  scale_x_continuous(limits = c(0, 100), breaks=seq(0, 100, 10)) +
  ggtitle("Return on investment") +
  gglayers +
  theme(plot.margin=unit(c(0.25,0.25,-0.25,0.25), "cm"))

# Return on equity
roe <- financials_amakudari %>%
  ggplot(aes(x = roe, y = amakudari, fill = ..x..)) +
  geom_density_ridges_gradient(scale = 2, rel_min_height = 0.005,
                               gradient_lwd = 2, color = "white", size = 0.05) +
  scale_fill_viridis(alpha = 0.8) +
  scale_x_continuous(limits = c(0, 30), breaks=seq(0, 30, 5)) +
  ggtitle("Return on equity") +
  gglayers +
  theme(plot.margin=unit(c(0.25,0.25,-0.25, 1.5), "cm"))

# Reserve ratio
reserve_ratio <- financials_amakudari %>%
  ggplot(aes(x = reserve_ratio, y = amakudari, fill = ..x..)) +
  geom_density_ridges_gradient(scale = 2, rel_min_height = 0.005,
                               gradient_lwd = 2, color = "white", size = 0.05) +
  scale_fill_viridis(alpha = 0.8) +
  scale_x_continuous(limits = c(0, 500), breaks=seq(0, 500, 100)) +
  ggtitle("Reserve ratio") +
  gglayers +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank()) +
  theme(plot.margin=unit(c(0.25,0.25,-0.25, 1.5), "cm"))

financial_plots <-
  grid.arrange(employees, assets, liabilities, ebitda, roi, reserve_ratio,
               nrow = 3, ncol = 2)

# FIGURE 4: Distributions of financial indicators by amakudari status (2009-2019)
ggsave(file="figures/4_amakudari_financial_overview.pdf", financial_plots, 
       height = 4.5, width = 8)

# ==============================================================================
# CLEANING LOAN DATA FOR VISUALIZATION ----
# ==============================================================================

# Convert variables to correct data types
loans_covs <- loans_covs %>% 
  mutate_at(c(18:32), as.numeric) %>%
  select(amakudari_binary, amakudari_n, everything())

# Reduce to financials only
financials <- loans_covs %>% 
  select(nikkei_code, year, debt_long_public:debt_total_private, 
         total_assets:temp_employees,
         -variable_cost_total, -fixed_cost_total, industry)

# Reduce to main variables
loans_reduced <- loans_covs %>%
  select(amakudari_binary, amakudari_n, nikkei_code, year, firm_dest_en, 
         tse_code, industry, debt_total_public, debt_total_private,
         total_assets, total_liabilities, roe)

# ==============================================================================
# BALANCE BY AMAKUDARI AMONG FIRMS IN LOAN DATA ----
# ==============================================================================

# Keep variables to highlight only, and rename for production, and
# # Group by firm in order to examine average values by firm over all years
balance <- loans_covs %>%
  select(nikkei_code, amakudari_binary, amakudari_n, debt_total_public, debt_total_private,
         total_assets, total_liabilities, operating_revenue, gross_profit, ebitda,
         leverage, employees, temp_employees, roi, roe, reserve_ratio, industry) %>%
  group_by(nikkei_code) %>%
  summarize(
    amakudari_n = sum(amakudari_n),
    across(c(debt_total_public:reserve_ratio), ~ mean(.x, na.rm = TRUE))
  ) %>%
  mutate(amakudari = ifelse(amakudari_n > 0, 1, 0))

#### Balance table including missingness ####
balance <- balance %>%
  mutate(
    Missing = ifelse(is.na(total_assets), 1, 0),
    amakudari = if_else(amakudari == 1, "Amakudari", "No amakudari"),
    across(c(debt_total_public, debt_total_private, total_assets, 
             total_liabilities, operating_revenue, gross_profit, ebitda), 
           ~ .x/1000)
    ) %>%
  rename(
    `Number of amakudari` = amakudari_n,
    `Total government loans` = debt_total_public,
    `Total private loans` = debt_total_private, 
    `Total assets` = total_assets,
    `Total liabilities` = total_liabilities,
    Leverage = leverage, 
    `Gross profit` = gross_profit,
    `Operating revenue` = operating_revenue,
    Employees = employees,
    `Temporary employees` = temp_employees,
    EBITDA = ebitda,
    `Return on investment` = roi,
    `Return on equity` = roe,
    `Reserve ratio` = reserve_ratio
  )

# TABLE A4
loans_financials <- datasummary_balance(~amakudari,
                    data = balance,
                    fmt = 2,
                    dinm_statistic = "p.value",
                    output = 'latex') %>%
  gsub("<", "$<$", .) %>%
  kable_classic(full_width = F, html_font = "Times New Roman") %>%
  kable_styling(bootstrap_options = c("striped", "hover", "condensed"),
                font_size = 10) %>%
  row_spec(0, bold = TRUE)

save_kable(loans_financials, "tables/a4_amakudari_balance.tex")

# Calculate government to private loan ratio for non-amakudari vs. amakudari
means <- loans_covs %>%
  group_by(amakudari_binary) %>%
  summarise(mean_public = mean(debt_total_public),
            mean_private = mean(debt_total_private))

# In text calculations page 20
means$mean_public[2]/means$mean_public[1]
means$mean_private[2]/means$mean_private[1]

# ==============================================================================
# MISSINGNESS ----
# ==============================================================================

#### Visualization of missingness ####
miss <- financials %>% 
  select(-debt_total_private, -debt_long_private, -debt_short_public, 
         -debt_long_public, -debt_short_private) %>%
  rename(Year = year, `Nikkei code` = nikkei_code, 
         `Government loans` = debt_total_public, `Assets` = total_assets,
         `Liabilities` = total_liabilities, `Revenue` = operating_revenue,
         `Profit` = gross_profit, ROI = roi, EBITDA = ebitda, ROE = roe,
         Leverage = leverage, `Reserve ratio` = reserve_ratio, 
         Employees = employees, `Temporary employees` = temp_employees,
         Industry = industry)

#### FIGURE A8a: Over time ####
miss %>%
  gg_miss_fct(fct = Year) +
  xlab("") + ylab("") + theme(legend.position="none")
ggsave(file="figures/a8a_loan_missing_time.pdf", height = 4, width = 7)

#### FIGURE A8b: By industry ####
miss %>%
  filter(!is.na(Industry)) %>%
  select(-Year) %>%
  gg_miss_fct(fct = Industry) +
  xlab("") + ylab("") + 
  theme(legend.position="bottom", legend.box.margin=margin(-20,-10,-10,-10))
ggsave(file="figures/a8b_loan_missing_industry.pdf", height = 6, width = 7)

# ==============================================================================
# EXAMINE ALL FIRMS VS FIRMS WITH GOVERNMENT LOANS  ----
# ==============================================================================
# Keep variables to highlight only and rename for production
# Group by firm in order to examine average values by firm over all years
loans_balance <- covs_loans %>% 
  select(-(firm_dest_en:city), -date_founded, -variable_cost_total, 
         -fixed_cost_total, -debt_long_public, -debt_short_public, 
         -debt_long_private, -debt_short_private, 
         -(amakudari_n_Other:amakudari_binary_MOFA)) %>%
  mutate(across(c(debt_total_public, debt_total_private, 
                  total_assets, total_liabilities, ebitda, 
                  operating_revenue, gross_profit), ~ .x/1000)) %>%
  group_by(nikkei_code) %>%
  summarize(
    amakudari_n = sum(amakudari_n),
    across(c(total_assets:debt_total_private), ~ mean(.x, na.rm = TRUE))
  ) %>%
  mutate(
    govt_debt = ifelse(debt_total_public > 0, "Public loans", "No public loans"),
    mutate(across(everything(), ~ ifelse(is.nan(.), NA, .)))) %>%
  rename(
    `Number of amakudari` = amakudari_n,
    `Total government loans` = debt_total_public,
    `Total private loans` = debt_total_private, 
    `Total assets` = total_assets,
    `Total liabilities` = total_liabilities,
    Leverage = leverage,
    `Gross profit` = gross_profit,
    `Operating revenue` = operating_revenue,
    Employees = employees,
    `Temporary employees` = temp_employees,
    EBITDA = ebitda,
    `Return on investment` = roi,
    `Return on equity` = roe,
    `Reserve ratio` = reserve_ratio
  ) %>%
  select(-nikkei_code)
  
# TABLE A5: Create balance table
loans_balance <- datasummary_balance(~govt_debt,
                                     data = loans_balance,
                                     fmt = 2,
                                     dinm_statistic = "p.value",
                                     output = 'latex') %>%
  gsub("<", "$<$", .) %>%
  kable_classic(full_width = F, html_font = "Times New Roman") %>%
  kable_styling(bootstrap_options = c("striped", "hover", "condensed"),
                font_size = 10) %>%
  row_spec(0, bold = TRUE)

save_kable(loans_balance, "tables/a5_loans_balance.tex")
